import java.util.HashMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 死锁在jdk1.7中会出现?? - 未验证
 * jdk1.8未出现。会出现线程不安全的问题
 * @author fangjiaxiaoabi
 * @date 2020-05-23
 */
public class HashMapDeadLock {

    public static void main(String[] args) throws InterruptedException {
        for (int i = 0; i < 10000; i++) {
            main1();
        }
    }

    public static void main1() throws InterruptedException {
        Lock lock = new ReentrantLock();
        lock.lock();
        HashMap<String, String> hashMap = new HashMap<>(2);
        hashMap.put("5","5");

        Thread thread = new Thread(() -> hashMap.put("3", "3"));
        Thread thread1 = new Thread(() -> hashMap.put("7", "7"));
        thread.start();
        thread1.start();

        thread1.join();
        thread.join();
        System.out.println(hashMap);
        lock.unlock();
    }


    public static void main2() throws InterruptedException {
        ConcurrentHashMap<String, String> hashMap = new ConcurrentHashMap<>(2);
        hashMap.put("5","5");

        Thread thread = new Thread(() -> {
            hashMap.put("3", "3");
        });
        Thread thread1 = new Thread(() -> {
            hashMap.put("7", "7");
        });
        thread.start();
        thread1.start();

        thread1.join();
        thread.join();
        System.out.println(hashMap);
    }


}
